package lesson

import (
	"fmt"
	"log"
	"sync"
)

// 依赖注入和策略模式
var container = make(map[string]interface{})

func Register(key string, instance interface{}) {
	container[key] = instance
}
func Resolve(key string) interface{} {
	return container[key]
}

type Database interface {
	connect(dns string) error
	serve(serveFunc func() error) error
}

type MysqlOrm struct {
	defaultDNS string // 默认的 DNS 值
}

// NewMysqlOrm 构造函数，初始化默认 DNS
func NewMysqlOrm(defaultDNS string) *MysqlOrm {
	return &MysqlOrm{
		defaultDNS: defaultDNS,
	}
}
func (m *MysqlOrm) connect(dns string) error {
	// 如果未传入 dns，则使用默认值
	if dns == "" {
		dns = m.defaultDNS
	}
	// 实现连接逻辑
	log.Println("MysqlOrm connected to", dns)
	return nil
}

func (m *MysqlOrm) serve(serveFunc func() error) error {
	if serveFunc == nil {
		return fmt.Errorf("serve function is nil")
	}
	return serveFunc()
}

type MysqlService struct {
	orm Database
}

func NewMysqlService(orm Database) *MysqlService {
	return &MysqlService{
		orm: orm,
	}
}
func (ms *MysqlService) startup(fn func() error, dns ...string) {
	// 连接数据库
	var resolvedDNS string
	if len(dns) > 0 {
		resolvedDNS = dns[0] // 使用传入的 dns
	} else {
		resolvedDNS = "" // 不传 dns，使用默认值
	}

	if err := ms.orm.connect(resolvedDNS); err != nil {
		log.Printf("Failed to connect to database: %v\n", err)
		return
	}
	// 执行自定义的 serve 逻辑
	if err := ms.orm.serve(fn); err != nil {
		log.Printf("Failed to start service: %v\n", err)
	} else {
		log.Println("Service started successfully")
	}
}

// IOrm 工厂函数，封装依赖注册和解析逻辑
var (
	ormInstance *MysqlService
	once        sync.Once
)

func IOrm() *MysqlService {
	once.Do(func() {
		// 注册依赖
		Register("mysqlOrm", NewMysqlOrm("default-dns"))

		// 解析依赖
		orm := Resolve("mysqlOrm").(Database)

		// 创建并返回 MysqlService 实例
		ormInstance = NewMysqlService(orm)
	})
	return ormInstance
}
